<template>
	<div>
		<h3>高亮搜索关键词</h3>
		<el-input v-model="keyword" clearable placeholder="请输入关键词" style="width:200px"
			@keyup.enter.native="handleSearch">
		</el-input>
		<el-button @click="handleSearch">搜索</el-button>
		<ul>
			<li v-for="item in filterList" :key="item.id" v-html="item.name"></li>
		</ul>
	</div>
</template>

<script>
import { Input, Button } from 'element-ui';
import { getUuid, deepClone } from '../../utils'
export default {
	components: {
		ElInput: Input,
		ElButton: Button
	},
	data() {
		return {
			keyword: '',
			list: [
				{
					id: getUuid(),
					name: 'sdfsdfdsfds'
				},
				{
					id: getUuid(),
					name: '佛挡杀佛'
				},
				{
					id: getUuid(),
					name: '水电费水电费'
				},
				{
					id: getUuid(),
					name: '水电费水电费水电费发给过'
				},
				{
					id: getUuid(),
					name: '电饭锅大范甘迪苟富贵'
				}
			]
		}
	},
	computed: {
		filterList() {
			let data = deepClone(this.list)
			if (this.keyword) {
				let replaceReg = new RegExp(this.keyword, 'i')
				data = data.filter(item => {
					let r = item.name.match(replaceReg)
					if (r) {
						let replaceString = `<span style="color: #ed4014">${r[0]}</span>`
						item.name = item.name.replace(replaceReg, replaceString)
						return item
					}
				})
			}
			return data
		}
	},
	created() {
	},
	methods: {
		handleSearch() {
			const data = deepClone(this.list)
			if (this.keyword) {
				let replaceReg = new RegExp(this.keyword, 'i')
				this.filterList = data.filter(item => {
					let r = item.name.match(replaceReg)
					if (r) {
						let replaceString = `<span style="color: #ed4014">${r[0]}</span>`
						item.name = item.name.replace(replaceReg, replaceString)
						return item
					}
				})
			} else {
				this.filterList = data
			}
		},
		changeColor(str, keyword, color) {
			if (keyword) {
				let replaceReg = new RegExp(keyword, 'i')
				let i = replaceReg.test(str)
				let replaceString = `<span style="color: ${color}">${keyword}</span>`
				if (i) {
					str = str.replace(replaceReg, replaceString)
				}
			}
			return str
		}
	}
}
</script>

<style lang="less" scoped>
.hightLight {
	color: red;
}
</style>
